package org.jeecg.modules.controller.doctor;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.modules.dic.entity.DicBeGoodAt;
import org.jeecg.common.modules.dic.service.IDicBeGoodAtService;
import org.jeecg.common.modules.dic.vo.GoodResponseVo;
import org.jeecg.common.modules.doctor.entity.*;
import org.jeecg.common.modules.doctor.service.*;
import org.jeecg.common.modules.doctor.vo.DoctorRegisterRecordListVo;
import org.jeecg.common.modules.doctor.vo.DoctorRegisterVo;
import org.jeecg.common.modules.doctor.vo.DoctorReqVo;
import org.jeecg.common.modules.makeAppointment.entity.MakeAppointment;
import org.jeecg.common.modules.makeAppointment.entity.MakeAppointmentInfo;
import org.jeecg.common.modules.makeAppointment.service.IMakeAppointmentInfoService;
import org.jeecg.common.modules.makeAppointment.service.IMakeAppointmentService;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.ImageUrl;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.result.Result;
import org.jeecg.common.util.result.ResultMapper;
import org.jeecg.modules.controller.BaseController;
import org.jeecg.modules.data.Common;
import org.jeecg.modules.service.ApiDoctorService;
import org.jeecg.modules.service.ApiGoodService;
import org.jeecg.modules.vo.DoctorListResponseVo;
import org.jeecg.modules.vo.request.DoctorScheduleRequestVo;
import org.jeecg.modules.vo.respone.DoctorListByDepartmentVo;
import org.jeecg.modules.vo.respone.DoctorResponseVo;
import org.jeecg.modules.vo.respone.HospitalResponseVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.support.NullValue;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@RequestMapping("api/v1")
@Slf4j
public class DoctorController extends BaseController {
    @Resource
    public IDoctorWxUserinfoRelationService doctorWxUserinfoRelationService;

    @Resource
    public IDoctorService doctorService;
    @Resource
    private IDoctorExtendService  doctorExtendService;
    @Resource
    private ApiGoodService apiGoodService;
    @Resource
    private ApiDoctorService apiDoctorService;
    @Resource
    private IDoctorConfigService doctorConfigService;
    @Resource
    private IDicBeGoodAtService dicBeGoodAtService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private IMakeAppointmentInfoService iMakeAppointmentInfoService;
    @Resource
    private IMakeAppointmentService makeAppointmentService;
    @Resource
    private IDoctorRegisterService iDoctorRegisterService;
    @Resource
    private IDoctorRegisterRecordService doctorRegisterRecordService;
    @Resource
    private IDoctorRegisterHospitalService doctorRegisterHospitalService;
    /**
     * 患者关注的所有专家
     * @return
     */
    @RequestMapping("/doctor/list")
    public Result<?> doctorList(HttpServletRequest req) {

        Result<?> result = new Result<>();
        String url = Common.operateUrl("doctor/list");
        if(Objects.isNull(req.getHeader("X-Access-Token"))){
            result.setCode(250);
            result.setMsg(url);
            return result;
        }
        String openId = null;
        try{
            if(Objects.nonNull(getOpenId())){ openId = getOpenId(); }
        } catch (Exception e){
            log.error("getOpenId()获取信息失败",e);
        }
        if(Objects.isNull(openId)){
            openId = (String) redisUtil.get(req.getHeader("X-Access-Token"));
        }
        log.info("openId：{}",openId);
        if(Objects.isNull(openId)){
            result.setCode(250);
            result.setMsg(url);
            return result;
        }
        LambdaQueryWrapper<DoctorWxUserinfoRelation> query = Wrappers.lambdaQuery();
        query.eq(DoctorWxUserinfoRelation::getOpenid,openId);
        List<DoctorWxUserinfoRelation> doctorsWxUsers =  doctorWxUserinfoRelationService.list(query);

        if(doctorsWxUsers.size()==0){
            return  ResultMapper.<List<DoctorListResponseVo>>ok().setMsg("该患者暂时没有关注医生。");
        }
        List<DoctorListResponseVo> listResult = new ArrayList<DoctorListResponseVo>();
        for (DoctorWxUserinfoRelation   relation: doctorsWxUsers) {
            Doctor doctor = doctorService.getById(relation.getDoctorId());
            DoctorExtend extend = doctorExtendService.getByDoctorId(doctor.getId());
            DoctorListResponseVo vo = initDoctorListResponseVo(doctor,relation,extend);
            vo.setOpenid(openId);
            listResult.add(vo);
        }
        return ResultMapper.<List<DoctorListResponseVo>>ok().setData(listResult);
    }

    @GetMapping("/doctor/share")
    public Result shareDoctor(@RequestParam String doctorId){
        Doctor doctor = doctorService.getById(doctorId);
        if(doctor ==null){
            doctor = doctorService.getOne(Wrappers.lambdaQuery(Doctor.class).eq(Doctor::getDcId,doctorId).eq(Doctor::getStatus,"1"));
            doctorId = doctor.getId();
        }
        doctor.setHeadImg(ImageUrl.handle(doctor.getHeadImg()));
        DoctorResponseVo  vo = new DoctorResponseVo();
        BeanUtils.copyProperties(doctor,vo);
        if (Objects.nonNull(doctor.getDepartment())){
            DicBeGoodAt dicBeGoodAt = dicBeGoodAtService.getById(doctor.getDepartment());

            vo.setDepartmentStr(Objects.nonNull(dicBeGoodAt) ? dicBeGoodAt.getName() : "");
        }
        DoctorExtend doctorExtend  =doctorExtendService.getByDoctorId(doctorId);
        if (StringUtils.isNotBlank(doctorExtend.getGood())){
            vo.setGood(JSONUtil.toList(JSONUtil.parseArray(doctorExtend.getGood()), DoctorResponseVo.Good.class));
        }
        DoctorExtend extend = doctorExtendService.getByDoctorId(doctor.getId());
        vo.setIntroduction(extend.getIntroduction());
        vo.setIntroductionTitle(extend.getIntroductionTitle());
        vo.setGoodDesc(extend.getGoodDesc());
        vo.setSchedule(apiDoctorService.getDoctorScheduleByDoctorId(doctorId));

//         是否本属医院判断
//          1、判断第一执业医院是否为本属四家医院 是则判断是否有号源，否则无号源
//          2、是本属医院，则判断是否有号源，有则显示，没有则无号源
        String[] hospitalNames= {"北京东城中医医院","北京石景山八大处中西医结合医院","北京中研集团东城中医医院", "北京中研中医院","北京天使望京妇儿医院"," 北京天使望京妇儿医院","北京东城中医院","北京正中堂中医医院"};
        vo.setHospitalOrderNum("无号源");
        for (String str :hospitalNames ){
            if(str.contains(doctor.getHospital())){
                vo.setHospitalOrderNum("");
            }
        }
        //获取预约挂号费用
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        List<DoctorResponseVo.hospitalList> hospitalList = new ArrayList<>( );
        DoctorConfig doctorConfig = doctorConfigService.getByDoctorId(doctorId,true);
        //List<MakeAppointmentInfo> makeAppointmentInfo = iMakeAppointmentInfoService.list(Wrappers.lambdaQuery(MakeAppointmentInfo.class).eq(MakeAppointmentInfo::getDoctorId,doctor.getId()).eq(MakeAppointmentInfo::getDate,sdf.format(addDate(new Date()))));
        //1、获取所有医院渠道
        //2、根据医院id，判断该医院该医生七天内的挂号和视频是否有号源
        List<DoctorRegisterHospital>  doctorRegisterHospitals = doctorRegisterHospitalService.list();

        Date date = new Date();
        for(DoctorRegisterHospital hospital : doctorRegisterHospitals){
            DoctorResponseVo.hospitalList hos= new DoctorResponseVo.hospitalList();
            //判断7天内是否有挂号号源
            List<DoctorRegisterVo> hospitals = iDoctorRegisterService.getDoctorRegisterHospital(doctorId,sdf.format(date),sdf.format(addDate15(new Date())),hospital.getId());
            //判断7天内是否有视频号源
            List<MakeAppointment> makeAppointments = makeAppointmentService.list(Wrappers.lambdaQuery(MakeAppointment.class).eq(MakeAppointment::getDoctorId,doctorId).eq(MakeAppointment::getRegisterHospitalId,hospital.getId()).ge(MakeAppointment::getDate,sdf.format(date)).le(MakeAppointment::getDate,sdf.format(addDate15(new Date()))));
            //同时为空，医院不显示
            if(hospitals.isEmpty()&&makeAppointments.isEmpty()){
                continue;
            }
            date = addDate(new Date());
            hos.setHospitalId(hospital.getId());
            hos.setHospitalName(hospital.getName());
            hos.setYuyueguahao(!hospitals.isEmpty()? hospitals.get(0).getPrice()+"":null);
            hos.setIshaveYuYue(!hospitals.isEmpty()? "1":null);
            hos.setTuwenzixun(doctorConfig.getTextMoney() + "");
            hos.setIshaveTuwen("1");
            hos.setShipinwenzhen(doctorConfig.getVideoMoney() + "");
            hos.setIshaveShiPin(!makeAppointments.isEmpty()?"1":null);
            hospitalList.add(hos);
        }
        vo.setHospitalList(hospitalList);
        if(hospitalList.size()>0){

        }
        return ResultMapper.ok().setData(vo);
    }
    /**
     * 获取医生详情
     * @return
     */
    @RequestMapping("/doctor/detail")
    public Result getDoctorById(@RequestParam("doctorId") String doctorId ,
                                HttpServletRequest req){
        Result<?> result = new Result<>();
        String[] strs = doctorId.split("-");
        String doctorId1 = strs[0];
        Doctor doctor = doctorService.getById(doctorId1);
        if(Objects.isNull(doctor)){
            return ResultMapper.<String>ok().setMsg("医生不存在。");
        }
//        String openId = getOpenId();
        DoctorWxUserinfoRelation relation = null;

//        if(Objects.isNull(relation)){
//            return ResultMapper.<String>ok().setMsg("您暂时没有关注医生。");
//        }
        DoctorExtend extend = doctorExtendService.getByDoctorId(doctorId1);
        DoctorListResponseVo vo = initDoctorListResponseVo(doctor,relation,extend);
        DoctorConfig config = doctorConfigService.getByDoctorId(doctorId1,false);
        vo.setTextMoney(config.getTextMoney());

        vo.setVideoMoney(config.getVideoMoney());
        vo.setSchedule(apiDoctorService.getDoctorScheduleByDoctorId(doctorId1));
        List<MakeAppointmentInfo> list = iMakeAppointmentInfoService.list(Wrappers.lambdaQuery(MakeAppointmentInfo.class).eq(MakeAppointmentInfo::getDoctorId,doctorId1).orderByAsc(MakeAppointmentInfo::getStartTime));
        vo.setList(list);
        return ResultMapper.<DoctorListResponseVo>ok().setData(vo);
    }


    @RequestMapping("/allGood")
    public Result<List<GoodResponseVo>> getGoods() {
        return apiGoodService.getAll();
    }

    @GetMapping("getDoctorListByDepartmentId")
    public Result<List<DoctorListByDepartmentVo>> getDoctorListByDepartmentId(@RequestParam("id") String id ){
            List<DoctorListByDepartmentVo> result = new ArrayList<>();
            List<DicBeGoodAt> departments = apiGoodService.getAllByDepartment(id);  //获取当前科室id的信息
            for (DicBeGoodAt department:departments) {
                DoctorListByDepartmentVo doctorListByDepartmentVo = new DoctorListByDepartmentVo();
                List<Doctor> doctors = doctorService.getDoctorByDepartmentId(department.getId());  //获取当前科室下的所有医生信息
                List<DoctorExtend> extendList = doctorExtendService.getByDoctorIds(doctors.stream().map(Doctor::getId).collect(Collectors.toList())); //获取医生的扩展信息（介绍和擅长）

                Map<String,DoctorExtend> map = extendList.stream().collect(Collectors.toMap(DoctorExtend::getDoctorId, Function.identity(),(a, b) -> a));
                List<DoctorListResponseVo> listResult = doctors.stream().map(item -> {
                    DoctorListResponseVo vo = initDoctorListResponseVo(item,null,map.get(item.getId()));
                    return vo;
                }).collect(Collectors.toList());
                doctorListByDepartmentVo.setId(department.getId());
                doctorListByDepartmentVo.setName(department.getName());
                doctorListByDepartmentVo.setImg(department.getImg());
                doctorListByDepartmentVo.setSort(department.getSort());
                doctorListByDepartmentVo.setDoctors(listResult);
                result.add(doctorListByDepartmentVo);

        }

        return ResultMapper.<List<DoctorListByDepartmentVo>>ok().setData(result);
    }


    /**
     * 获取二级列表，病种
     *
     * @param id
     * @return
     */
    @GetMapping("getSecondListByParentId")
    public List<DicBeGoodAt> getSecondListByParentId(@RequestParam("id") String id ){
        return apiGoodService.getAllByParentId(id);
    }

    /**
     * 根据病种或关键字 获取对应医生
     *
     * @param keyword ,
     * @return
     */
    @GetMapping("getDoctorsByKeyWord")
    public List<DoctorReqVo> getDoctorsByKeyWord(@RequestParam("keyword") String  keyword, @RequestParam("goodDesc") String goodDesc){
        List<DoctorReqVo> doctorReqVos = new ArrayList<>(   );
        if(keyword.equals("") && !goodDesc.equals("")){
            doctorReqVos = doctorService.getDoctorsByGoodDesc(goodDesc);
        }else{
            doctorReqVos = doctorService.getDoctorsByKeyWord(keyword,goodDesc);
        }

        return doctorReqVos;
    }


    /**
     * 获取医生排班
     * @param accessToken
     * @return
     */
    @GetMapping("doctorSchedule")
    public Result<List<HospitalResponseVo>> doctorSchedule(@RequestParam("accessToken") String accessToken,String doctorId){
        return apiDoctorService.getDoctorSchedule(accessToken,doctorId);
    }

    @PostMapping("doctorSchedule")
    public Result<NullValue> doctorSchedule(@RequestBody DoctorScheduleRequestVo request){
        return apiDoctorService.setDoctorSchedule(request);
    }
    private DoctorListResponseVo initDoctorListResponseVo(Doctor doctor,DoctorWxUserinfoRelation relation,DoctorExtend extend){
        DoctorListResponseVo vo = new DoctorListResponseVo();
        vo.setBusinessType(doctor.getBusinessType());
        vo.setCertificationStatus(doctor.getCertificationStatus());
        vo.setCityId(doctor.getCityId());
        vo.setHeadImg(ImageUrl.handle(doctor.getHeadImg()));
        DicBeGoodAt dicBeGoodAt = dicBeGoodAtService.getById(doctor.getDepartment());
        if (Objects.nonNull(dicBeGoodAt)){
            vo.setDepartment(dicBeGoodAt.getName());
        }
        vo.setMaster(doctor.getMaster());
        vo.setHospital(doctor.getHospital());
        vo.setName(doctor.getName());
        vo.setOpenid(doctor.getOpenid());
        vo.setProvinceId(doctor.getProvinceId());
        vo.setSex(doctor.getSex());
        vo.setTitle(doctor.getTitle());
        vo.setGood(extend.getGood());
        vo.setQrCode(doctor.getQrCode());
        vo.setDoctorId(doctor.getId());
        vo.setIntroduction(extend.getIntroduction());
        String introductionTitles = extend.getIntroductionTitle();
        List<Map<String,String>> list = new ArrayList<>();
        if(StringUtils.isNoneEmpty(introductionTitles)){
           String titles[] = introductionTitles.replaceAll("，",",").split(",");
            for (String title:titles) {
                Map<String,String> map = new HashMap<>();
                map.put("name",title);
                list.add(map);
            }
        }
        vo.setGoodDesc(extend.getGoodDesc());
        vo.setIntroductionTitles(list);
        if (Objects.nonNull(relation)){
            vo.setTextNumber(relation.getTextNumber());
            vo.setVideoNumber(relation.getVideoNumber());
            vo.setVideoRoomId(relation.getVideoRoomId());
            vo.setImGroupId(relation.getImGroupId());
        }
        return vo;
    }
    @GetMapping("/doctor/buyService")
    public Result buyService(@RequestParam String doctorId, String registerHospitalId){
        Doctor doctor = doctorService.getById(doctorId);
        if(doctor ==null){
            doctor = doctorService.getOne(Wrappers.lambdaQuery(Doctor.class).eq(Doctor::getDcId,doctorId).eq(Doctor::getStatus,"1"));
            doctorId = doctor.getId();
            registerHospitalId="1452811085769940994";
        }
        doctor.setHeadImg(ImageUrl.handle(doctor.getHeadImg()));
        DoctorResponseVo  vo = new DoctorResponseVo();
        BeanUtils.copyProperties(doctor,vo);
        if (Objects.nonNull(doctor.getDepartment())){
            DicBeGoodAt dicBeGoodAt = dicBeGoodAtService.getById(doctor.getDepartment());
            vo.setDepartmentStr(Objects.nonNull(dicBeGoodAt) ? dicBeGoodAt.getName() : "");
        }
        DoctorExtend doctorExtend  =doctorExtendService.getByDoctorId(doctorId);
        if (StringUtils.isNotBlank(doctorExtend.getGood())){
            vo.setGood(JSONUtil.toList(JSONUtil.parseArray(doctorExtend.getGood()), DoctorResponseVo.Good.class));
        }
        DoctorRegisterHospital hostpiatl = doctorRegisterHospitalService.getById(registerHospitalId);
        if(hostpiatl != null){
            vo.setRegisterHospital(hostpiatl.getName());
        }
        DoctorExtend extend = doctorExtendService.getByDoctorId(doctor.getId());
        vo.setIntroduction(extend.getIntroduction());
        vo.setIntroductionTitle(extend.getIntroductionTitle());
        vo.setGoodDesc(extend.getGoodDesc());
        vo.setSchedule(apiDoctorService.getDoctorScheduleByDoctorId(doctorId));

        //获取7天数据，并拼接日期
        List<DoctorResponseVo.order> orders = new ArrayList<>();
        DoctorRegisterVo doctorRegisterVo = new DoctorRegisterVo();
        doctorRegisterVo.setDoctorId(doctorId);
        doctorRegisterVo.setRegisterHospitalId(registerHospitalId);
        Date now = new Date();
        now = addDate(now);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for(int i=1;i<=15;i++){

           DoctorResponseVo.order order = new DoctorResponseVo.order();
            if(i == 15){
                Date nowDate = new Date();  //当前时间
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm");
                SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String date = sdf.format(now)+ CommonUtils.BEGINTIME;
                try {
                    Date date1 = sdf3.parse(date);
                    Date date2 = sdf3.parse(sdf.format(now)  +" "+sdf2.format(nowDate));
                    System.out.println(date1.getTime());
                    System.out.println(date2.getTime());
                    if(date1.getTime()-date2.getTime()>=0){
                        order.setIsBegin(1);
                    }else{
                        order.setIsBegin(0);
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }else{
                order.setIsBegin(0);
            }

            doctorRegisterVo.setVisitTime(sdf.format(now));
            List<DoctorRegisterVo> doctorRegisterVos = iDoctorRegisterService.queryOrderIsHave(doctorRegisterVo);
            order.setDate(sdf.format(now));
            order.setWeek(getWeekOfDate(now));
            order.setDoctorId(doctorId);
            if(doctorRegisterVos !=  null && !doctorRegisterVos.isEmpty()){
                order.setId(doctorRegisterVos.get(0).getId());
                if("1".equals(doctorRegisterVos.get(0).getIshave())){
                    order.setDoctorRegisterId(doctorRegisterVos.get(0).getId());
                    order.setIsHave("有号");
                }else {
                    order.setIsHave("约满");
                }
            }else{
                order.setIsHave("暂无号源");
            }
            order.setRegisterHospitalId(registerHospitalId);
            now = addDate(now);
            orders.add(order);
        }
        vo.setOrderList(orders);
        return ResultMapper.ok().setData(vo);
    }
    /**
     * 获取工作时间段详情
     * */
    @GetMapping("/doctor/getOrderDetail")
    public Result getOrderDetail(@RequestParam String doctorId, String visitTime, String registerHospitalId){
        log.info("visitTime:"+visitTime);
        log.info("doctorId:"+visitTime);
        log.info("replaceAll:"+visitTime.replaceAll("年","-").replaceAll("月","-").replaceAll("日",""));
        List<DoctorRegisterRecordListVo> doctorRegisterRecordListVos = doctorRegisterRecordService.getRegisterRecordTime(doctorId, visitTime.replaceAll("年","-").replaceAll("月","-").replaceAll("日",""), registerHospitalId);
        if(doctorRegisterRecordListVos ==null||doctorRegisterRecordListVos.size() == 0){
            Doctor doctor = doctorService.getOne(Wrappers.lambdaQuery(Doctor.class).eq(Doctor::getDcId,doctorId).eq(Doctor::getStatus,"1"));
            doctorId = doctor.getId();
            registerHospitalId="1452811085769940994";
            doctorRegisterRecordListVos = doctorRegisterRecordService.getRegisterRecordTime(doctorId, visitTime.replaceAll("年","-").replaceAll("月","-").replaceAll("日",""), registerHospitalId);

        }
        for (DoctorRegisterRecordListVo vo:doctorRegisterRecordListVos){
            vo.setStartTime(vo.getStartTime().substring(0,5));
            vo.setEndTime(vo.getEndTime().substring(0,5));
        }
        log.info("doctorRegisterRecordListVos:"+doctorRegisterRecordListVos);
        return ResultMapper.ok().setData(doctorRegisterRecordListVos);
    }

    /***
     * 日期+1天
     * @param date
     * @return
     */
    private Date addDate(Date date){
         return new Date(date.getTime() + 1000 * 60 * 60 * 24 * 1);
    }
    /***
     * 日期+1天
     * @param date
     * @return
     */
    private Date addDate15(Date date){
        return new Date(date.getTime() + 1000 * 60 * 60 * 24 * 1 * 15);
    }
    /**
     * 获取当前日期是星期几<br>
     *
     * @param dt
     * @return 当前日期是星期几
     */
    public String getWeekOfDate(Date dt) {
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }
//
    /**
     * 获取我的医生
     * */
    @GetMapping("/doctor/queryMyDoctors")
    public Result queryMyDoctors(@RequestParam String openid){
        List<DoctorReqVo> myDoctors = doctorService.queryMyDoctors(openid);
        if(!myDoctors.isEmpty()){
            for (DoctorReqVo vo:myDoctors){
                DoctorReqVo doctorReqVo = new DoctorReqVo();
                List<Map<String,String>> list = new ArrayList<>();
                String intr = vo.getIntroductionTitle();
                if(intr == null){
                    continue;
                }
                String titles[] = intr.replaceAll("，",",").split(",");
                for (String title:titles) {
                    Map<String,String> map = new HashMap<>();
                    map.put("name",title);
                    list.add(map);
                }
                vo.setIntroductionTitles(list);
            }
        }
        System.out.println(myDoctors);
        return ResultMapper.ok().setData(myDoctors);
    }
    /**
     * 获取医生详情
     * @return
     */
    @RequestMapping("/doctor/detailSP")
    public Result getDetailSP(@RequestParam String doctorId){
        Doctor doctor = doctorService.getById(doctorId);
        doctor.setHeadImg(ImageUrl.handle(doctor.getHeadImg()));
        DoctorResponseVo  vo = new DoctorResponseVo();
        BeanUtils.copyProperties(doctor,vo);
        if (Objects.nonNull(doctor.getDepartment())){
            DicBeGoodAt dicBeGoodAt = dicBeGoodAtService.getById(doctor.getDepartment());
            vo.setDepartmentStr(Objects.nonNull(dicBeGoodAt) ? dicBeGoodAt.getName() : "");
        }
        DoctorExtend doctorExtend  =doctorExtendService.getByDoctorId(doctorId);
        if (StringUtils.isNotBlank(doctorExtend.getGood())){
            vo.setGood(JSONUtil.toList(JSONUtil.parseArray(doctorExtend.getGood()), DoctorResponseVo.Good.class));
        }

        DoctorExtend extend = doctorExtendService.getByDoctorId(doctor.getId());
        vo.setIntroduction(extend.getIntroduction());
        vo.setIntroductionTitle(extend.getIntroductionTitle());
        vo.setGoodDesc(extend.getGoodDesc());
        vo.setSchedule(apiDoctorService.getDoctorScheduleByDoctorId(doctorId));

        //获取7天数据，并拼接日期
        List<DoctorResponseVo.order> orders = new ArrayList<>();
        MakeAppointment makeAppointment = new MakeAppointment();
        makeAppointment.setDoctorId(doctorId);
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for(int i=1;i<=7;i++){
            DoctorResponseVo.order order = new DoctorResponseVo.order();
            order.setWeek(getWeekOfDate(now));
            MakeAppointment makeAppointment1 = makeAppointmentService.getOne(Wrappers.lambdaQuery(MakeAppointment.class).like(MakeAppointment::getDate,sdf.format(now)).eq(MakeAppointment::getDoctorId,doctorId).groupBy(MakeAppointment::getDate));
            if(makeAppointment1 !=  null){
                order.setVartPart(makeAppointment1.getVartPart());
                if(makeAppointment1.getSurplus() > 0){
                    order.setIsHave("有号");
                }else {
                    order.setIsHave("约满");
                }
            }else{
                order.setIsHave("停止挂号");
            }
            order.setDate(sdf.format(now));
            order.setDoctorId(doctorId);

            now = addDate(now);
            orders.add(order);
        }
        vo.setOrderList(orders);
        return ResultMapper.ok().setData(vo);
    }
    /**
     * 获取工作时间段详情
     * */
    @GetMapping("/doctor/getOrderDetailSP")
    public Result getOrderDetailSP(@RequestParam String doctorId, String date){
        log.info("doctorId:"+doctorId);
        log.info("date:"+date);
        List<MakeAppointment> make = makeAppointmentService.list(Wrappers.lambdaQuery(MakeAppointment.class).eq(MakeAppointment::getDoctorId,doctorId).like(MakeAppointment::getDate, date.replaceAll("年","-").replaceAll("月","-").replaceAll("日","")));
        List<MakeAppointmentVO> makeAppointmentVOS = new ArrayList<>(   );
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        for (MakeAppointment m:make) {
            MakeAppointmentVO makeAppointmentVO = new MakeAppointmentVO();
            BeanUtils.copyProperties(m,makeAppointmentVO);
            makeAppointmentVO.setStartTimeNew(sdf.format(m.getStartTime()));
            makeAppointmentVO.setEndTimeNew(sdf.format(m.getEndTime()));
            makeAppointmentVOS.add(makeAppointmentVO);
        }
        log.info("makeAppointmentVOS:"+makeAppointmentVOS);
        return ResultMapper.ok().setData(makeAppointmentVOS);
    }
    @GetMapping("/doctor/buyServiceNew")
    public Result buyServiceNew(@RequestParam String doctorId, String registerHospitalId){
//        doctorId = "76076e0419e14698aa5b8c8258608a78";
        registerHospitalId = "1452811085769940994";
        Doctor doctor = doctorService.getById(doctorId);
        if(doctor ==null){
            doctor = doctorService.getOne(Wrappers.lambdaQuery(Doctor.class).eq(Doctor::getDcId,doctorId).eq(Doctor::getStatus,"1"));
            doctorId = doctor.getId();
            registerHospitalId="1452811085769940994";
        }
        doctor.setHeadImg(ImageUrl.handle(doctor.getHeadImg()));
        DoctorResponseVo  vo = new DoctorResponseVo();
        BeanUtils.copyProperties(doctor,vo);
        if (Objects.nonNull(doctor.getDepartment())){
            DicBeGoodAt dicBeGoodAt = dicBeGoodAtService.getById(doctor.getDepartment());
            vo.setDepartmentStr(Objects.nonNull(dicBeGoodAt) ? dicBeGoodAt.getName() : "");
        }
        DoctorExtend doctorExtend  =doctorExtendService.getByDoctorId(doctorId);
        if (StringUtils.isNotBlank(doctorExtend.getGood())){
            vo.setGood(JSONUtil.toList(JSONUtil.parseArray(doctorExtend.getGood()), DoctorResponseVo.Good.class));
        }
        DoctorRegisterHospital hostpiatl = doctorRegisterHospitalService.getById(registerHospitalId);
        if(hostpiatl != null){
            vo.setRegisterHospital(hostpiatl.getName());
        }
        DoctorExtend extend = doctorExtendService.getByDoctorId(doctor.getId());
        vo.setIntroduction(extend.getIntroduction());
        vo.setIntroductionTitle(extend.getIntroductionTitle());
        vo.setGoodDesc(extend.getGoodDesc());
        vo.setSchedule(apiDoctorService.getDoctorScheduleByDoctorId(doctorId));


        DoctorRegisterVo doctorRegisterVo = new DoctorRegisterVo();
        doctorRegisterVo.setDoctorId(doctorId);
        doctorRegisterVo.setRegisterHospitalId(registerHospitalId);
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<DoctorResponseVo.visitTime> visitTimeList = new ArrayList<>();
        for(int i=1;i<=7;i++) {
            //获取7天数据，并拼接日期
            List<DoctorResponseVo.order> orders = new ArrayList<>();
            now = addDate(now);
            DoctorResponseVo.visitTime visitTime = new DoctorResponseVo.visitTime();
            visitTime.setVisitTime(now);
            List<String> vartPart = new ArrayList<>();
            vartPart.add("全天");
            vartPart.add("上午");
            vartPart.add("下午");
            vartPart.add("晚上");
            List<DoctorRegisterVo> doctorRegisterVos = null;
            doctorRegisterVo.setVisitTime(sdf.format(now));
            for (String v : vartPart) {
                DoctorResponseVo.order order = new DoctorResponseVo.order();
                doctorRegisterVo.setVisitPart(v);
                doctorRegisterVos = iDoctorRegisterService.queryOrderIsHaveNew(doctorRegisterVo);
                order.setDate(sdf.format(now));
                order.setWeek(getWeekOfDate(now));
                order.setDoctorId(doctorId);
                if ("全天".equals(v)) {
                    if ( doctorRegisterVos !=  null && !doctorRegisterVos.isEmpty() &&"1".equals(doctorRegisterVos.get(0).getIshave())) {
                        DoctorResponseVo.order order1 = new DoctorResponseVo.order();
                        order1.setDate(sdf.format(now));
                        order1.setWeek(getWeekOfDate(now));
                        order1.setDoctorId(doctorId);
                        order1.setDoctorRegisterId(doctorRegisterVos.get(0).getId());
                        order1.setIsHave("有号");
                        order1.setRegisterHospitalId(registerHospitalId);
                        order1.setVartPart("上午");
                        orders.add(order1);

                        DoctorResponseVo.order order2 = new DoctorResponseVo.order();
                        order2.setDate(sdf.format(now));
                        order2.setWeek(getWeekOfDate(now));
                        order2.setDoctorId(doctorId);
                        order2.setDoctorRegisterId(doctorRegisterVos.get(0).getId());
                        order2.setIsHave("有号");
                        order2.setRegisterHospitalId(registerHospitalId);
                        order2.setVartPart("下午");
                        orders.add(order2);

                        DoctorResponseVo.order order3 = new DoctorResponseVo.order();
                        order3.setDate(sdf.format(now));
                        order3.setWeek(getWeekOfDate(now));
                        order3.setDoctorId(doctorId);
                        order3.setDoctorRegisterId(doctorRegisterVos.get(0).getId());
                        order3.setIsHave("无号");
                        order3.setRegisterHospitalId(registerHospitalId);
                        order3.setVartPart("晚上");
                        orders.add(order3);
                        break;
                    }
                }
                if ("上午".equals(v)) {
                    order.setVartPart(v);
                    if (doctorRegisterVos !=  null && !doctorRegisterVos.isEmpty() &&"1".equals(doctorRegisterVos.get(0).getIshave())) {
                        order.setDoctorRegisterId(doctorRegisterVos.get(0).getId());
                        order.setIsHave("有号");
                        order.setRegisterHospitalId(registerHospitalId);
                    } else {
                        order.setIsHave("无号");
                    }
                    orders.add(order);
                } else if ("下午".equals(v)) {
                    order.setVartPart(v);
                    if (doctorRegisterVos !=  null && !doctorRegisterVos.isEmpty() &&"1".equals(doctorRegisterVos.get(0).getIshave())) {
                        order.setDoctorRegisterId(doctorRegisterVos.get(0).getId());
                        order.setIsHave("有号");
                        order.setRegisterHospitalId(registerHospitalId);
                    } else {
                        order.setIsHave("无号");
                    }
                    orders.add(order);
                } else if ("晚上".equals(v)) {
                    order.setVartPart(v);
                    if (doctorRegisterVos !=  null && !doctorRegisterVos.isEmpty() &&"1".equals(doctorRegisterVos.get(0).getIshave())) {
                        order.setDoctorRegisterId(doctorRegisterVos.get(0).getId());
                        order.setIsHave("有号");
                        order.setRegisterHospitalId(registerHospitalId);
                    } else {
                        order.setIsHave("无号");
                    }
                    orders.add(order);
                }
            }
            visitTime.setOrders(orders);
            visitTimeList.add(visitTime);
        }
        vo.setVisitTimeList(visitTimeList);
        return ResultMapper.ok().setData(vo);
    }
}
